package com.ljsw.activity;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import com.ljsw.dialog.DeleteDialog;
import com.ljsw.dialog.LoginDialog;
import com.ljsw.dialog.SuccessDialog;
import com.ljsw.update.version.GetPDA;
import com.ljsw.update.version.Loading;
import com.ljsw.update.version.Online;
import com.ljsw.update.version.VersionInfo;
import com.ljsw.url.ServerUrl;
import com.ljsw.util.DialogManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
* @Package com.ljsw.activity 
* @Description: TODO(版本更新检测) 
* @author 郑鸿博   
* @date 2015-12-10 下午3:36:44 
* @version V1.0
 */
public class VersionCheckActivity extends Activity{
	
	TextView versionNum;
	Button btn;
	private GetPDA Pda;
	private DialogManager manager;
	Loading on;	
	Handler handler=null;  //获取版本号
	public static boolean stopupdate=true;
	private LoginDialog dialog;
	private DeleteDialog dDialog;
	private SuccessDialog sDialog;
	SharedPreferences sharepre;
	String space;   //空间
	String webservice;  //webservice地址
	private boolean install;
	
	GetPDA getPda(){
		if(Pda==null){
			Pda = new GetPDA();
		}
		return Pda;
	}
	Online online = new Online();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_version_check);
		manager =new DialogManager(this);
		on = new Loading(this).builder();
		dialog = manager.getLoginDialog();
		dDialog = manager.getDeleteDialog();
		sDialog = manager.getSuccessDialog();
		btn = (Button) findViewById(R.id.checkupdate);
		versionNum = (TextView) findViewById(R.id.version);
		versionNum.setText("当前版本"+getVersion());
			
	
		
		
		//更新按钮
		btn.setOnTouchListener(new View.OnTouchListener() {			
			
			public boolean onTouch(View view, MotionEvent even) {
				switch(even.getAction()){
				case MotionEvent.ACTION_DOWN:
					btn.setBackgroundResource(R.drawable.gray_btn_bg_press);
					break;
				case MotionEvent.ACTION_UP:
					btn.setBackgroundResource(R.drawable.gray_btn_bg);
					dialog.show();
					dialog.setMessage("正在获取新版本");					
				    getPda().getpath(handler,VersionCheckActivity.this);
				    
					break;
				case MotionEvent.ACTION_CANCEL:
					btn.setBackgroundResource(R.drawable.gray_btn_bg);
					break;								
				}					
				return true;
			}
		});
				
		 //通知安装新版本
		 final Handler h_load = new Handler(){
			@Override
			public void handleMessage(Message msg) {				
				super.handleMessage(msg);
				//取消计时器
				new Online().t.cancel();
				if(msg.what==100){
					if(!install){
						install = true;
						Timer t = new Timer();
						t.schedule(new TimerTask() {						
							@Override
							public void run() {																			
								installAPK();								
							}
						}, 2500);
					}																				
				}
			}
			 
		 };
		 
		 
		 //获取版本号并更新
		    handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				dialog.dismiss();
				switch(msg.what){
				case -1:
					dDialog.show();
					dDialog.setTitle("版本获取失败，是否重新获取？");
					dDialog.setPositiveButton("确定", new OnClickListener() {
						
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							dialog.show();
							dialog.setMessage("正在获取新版本");					
						    getPda().getpath(handler,VersionCheckActivity.this);
						}
					}).setNegativeButton("取消", new OnClickListener() {
						
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							
						}
					});
					break;
				case 99:
					dDialog.show();
					dDialog.setTitle("发现新版本，是否现在更新？");
					dDialog.setPositiveButton("确定", new OnClickListener() {
						
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							on.loading(VersionCheckActivity.this, h_load);
						}
					}).setNegativeButton("取消", new OnClickListener() {
						
						public void onClick(View arg0) {
							// TODO Auto-generated method stub
							
						}
					});
					break;
				case 44:
					sDialog.show();
					sDialog.success();
					sDialog.setSuTitle("目前已是最高版本");
					sDialog.setSuccess(new OnClickListener() {					
						public void onClick(View arg0) {
							// TODO Auto-generated method stub			
						}
					});
					break;
				}	
			}		 
		 };																							
	}
	
	//安装应用程序
		public void installAPK(){
			String paths = Environment.getExternalStorageDirectory()+"/PDA_Version"+"/"+VersionInfo.APKNAME;
			//String paths = Environment.getExternalStorageDirectory()+"/PDA_Version"+"/PDAA20.apk";
			File file = new File(paths);
			if(file.exists()){

				Intent intent = new Intent(Intent.ACTION_VIEW);
				try {
					intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");	
					startActivity(intent);
					VersionCheckActivity.this.finish();
				} catch (Exception e) {
					e.getCause();
					System.out.println(e.getMessage());
				}
			}
		}
		
		public String getVersion(){
			String versioncode="";
			    PackageManager packageManager = VersionCheckActivity.this.getPackageManager();
				PackageInfo info;
				try {
					info = packageManager.getPackageInfo(VersionCheckActivity.this.getPackageName(), 0);
					//当前版本号
					versioncode = info.versionName;
					Log.i("versioncode当前版本号",versioncode+"");
				} catch (NameNotFoundException e) {
			
					e.printStackTrace();
				}
				
				
				return versioncode;
		}
		
		
		
		
		
		@Override
		public void onBackPressed() {
			super.onBackPressed();
			stopupdate = false;
			online.t.cancel();
			on.dismiss();
		}
		@Override
		protected void onStart() {
			super.onStart();
			stopupdate = true;	
			//获取空间和web服务地址
			sharepre = getSharedPreferences("web", Context.MODE_PRIVATE);			
			space = sharepre.getString("space","");
			webservice = sharepre.getString("webservice","");	
			if(space!=null && space!="" && webservice!=null && webservice!=""){
				ServerUrl.URL = webservice;
				ServerUrl.NAMESPACE = space;
			}else{
				
			}
		}	
}

